package com.self.redis;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 作者：tianjiayuan
 * 创建时间：2018-06-08 14:37
 * 类描述：
 * 修改人：
 * 修改时间：
 */
public class RedisAtom {

    private JedisCluster jedisCluster;

    private AtomicInteger count = new AtomicInteger(1);

    public RedisAtom() {
        jedisCluster = new JedisCluster(new HostAndPort("192.168.1.215", 7379), 2000, 500, 50, "nep@admin", new JedisPoolConfig());
    }

    public void runTest(int nums) {
        for (int i=0; i < nums; i++) {
            new Thread(new RunJob()).start();
        }
    }

    public String getValue(String key) {
        return this.jedisCluster.get(key);
    }

    public void runFuthure() {
        FutureTask<Integer> futureTask = new FutureTask<Integer>(new RunFuthure());

        new Thread(futureTask).start();

        try {
            System.out.println(futureTask.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class RunJob implements Runnable {
        @Override
        public void run() {
            count.incrementAndGet();
            jedisCluster.set("count", count + "");
        }
    }

    private class RunFuthure implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            return 12;
        }
    }

    public static void main(String[] args) {
        RedisAtom redisAtom = new RedisAtom();

        redisAtom.runTest(5);

        System.out.println(redisAtom.getValue("count"));

        redisAtom.runFuthure();
    }
}
